package com.cangshi.filter;


import com.alibaba.fastjson.JSON;
import com.cangshi.entity.User;
import com.cangshi.entity.UserBaseInfo;
import com.cangshi.service.UserService;
import io.jsonwebtoken.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.security.Key;

import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by user on 2016-12-9.
 */
public class LoginFilter implements Filter {

    @Autowired
    UserService userService;

//    private static final Logger LOGGER = Logger.getLogger(LoginFilter.class);

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String authHeader = request.getHeader("Authorization");
        System.out.println("---------------------------------------------->>>>>>>>>>>" + authHeader);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {

            if (authHeader == null) {
                //设置错误代码
                request.setAttribute("error", 204);
                request.setAttribute("mes", "用户未进行登录验证");

            } else {
                //设置错误代码
                request.setAttribute("error", 201);
                request.setAttribute("mes", "用户登录验证格式非法");

            }
            //转发请求目的地
            request.getRequestDispatcher("/error").forward(request, response);


        } else {
            String token = authHeader.substring(7); // The part after "Bearer "
            try {
                Claims claims = Jwts.parser().setSigningKey("cangshi")
                        .parseClaimsJws(token).getBody();
                UserBaseInfo user = JSON.parseObject(claims.getSubject(), UserBaseInfo.class);
                UserBaseInfo checkUser = userService.getUserBaseInfoByUserId(user.getUserId());

                if (!(checkUser != null && user.equals(checkUser))) {
                    request.setAttribute("error", 211);
                    request.setAttribute("mes", "验证失败请重新登录");
                    //转发请求目的地
                    request.getRequestDispatcher("/error").forward(request, response);
                } else {
                    request.setAttribute("user", user);
                    request.setAttribute("error", 0);
                    request.setAttribute("mes", "登录成功");
                }

                //验证成功则允许指令
                filterChain.doFilter(servletRequest, servletResponse);
            } catch (SignatureException e) {
                //设置错误代码
                request.setAttribute("error", 202);
                request.setAttribute("mes", e.getMessage());
                //转发请求目的地
                request.getRequestDispatcher("/error").forward(request, response);
            } catch (MalformedJwtException e) {
                //设置错误代码
                request.setAttribute("error", 201);
                request.setAttribute("mes", e.getMessage());
                //转发请求目的地
                request.getRequestDispatcher("/error").forward(request, response);
            }
        }
    }

    public void destroy() {

    }
}
